package com.nijie.library.utils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * ${DESCRIPTION}
 *
 * @author
 * @create 2017-12-02 20:40
 **/
public class EmailUtil {
	private  static final String serveHost = "smtp.qq.com"; //qq邮箱服务地址
	//private  static final String fromoEmail = "3276596704@qq.com"; // 发送端邮箱地址
	//private  static final String password = "ktvdqmoxnohldaah"; // qq邮箱SMTP服务授权码

	private  static final String fromoEmail = "183521075@qq.com"; // 发送端邮箱地址
	private  static final String password = "wjiuvqefadqdbehf"; // qq邮箱SMTP服务授权码
	/**
	 * 用于发送对邮件信息
	 * @param emailAddress 目标邮箱地址
	 * @param title 邮件标题
	 * @param sendMsg 发送的邮箱内容
	 */
	public static void sendEmail(String emailAddress, String title, String sendMsg) throws Exception {

		Properties props = new Properties();
		// 开启debug调试
		//props.setProperty("mail.debug", "true");
		// 发送服务器需要身份验证
		props.setProperty("mail.smtp.auth", "true");
		// 设置邮件服务器主机名
		props.setProperty("mail.host", "smtp.qq.com");
		// 发送邮件协议名称
		props.setProperty("mail.transport.protocol", "smtp");

		//SSL认证，腾讯邮箱是基于SSL加密的，需要开启才可以使用
		MailSSLSocketFactory sf = new MailSSLSocketFactory();
		sf.setTrustAllHosts(true);
		props.put("mail.smtp.ssl.enable", "true");
		props.put("mail.smtp.ssl.socketFactory", sf);
		//创建会话
		Session session = Session.getInstance(props);
		//发送的消息，基于观察者模式进行设计的
		Message msg = new MimeMessage(session);
		msg.setSubject(title);

		//使用StringBuilder，因为StringBuilder加载速度会比String快，而且线程安全性也不错
		StringBuilder builder = new StringBuilder();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		builder.append(sendMsg);
		builder.append("\n" + df.format(new Date()));
		msg.setText(builder.toString());
		msg.setFrom(new InternetAddress(fromoEmail));
		Transport transport = session.getTransport();
		//发送端的QQ邮箱，邮箱开启SMTP服务申请的独立密码（授权码）
		transport.connect(serveHost, fromoEmail, password);
		//发送消息
		transport.sendMessage(msg, new Address[] { new InternetAddress(emailAddress) });
		transport.close();
	}
}
